﻿using LIU.Framework.Inject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Threading.Tasks;

namespace LIU.Framework.Cache
{
    /// <summary>
    /// 系统默认缓存
    /// </summary>
    public class SystemCache : ICache, IDefaultImplementation
    {
        /// <summary>
        /// 系统默认缓存
        /// </summary>
        public SystemCache()
        {
            cache = new MemoryCache(Name);
        }
        /// <summary>
        /// 内部缓存
        /// </summary>
        private readonly MemoryCache cache;

        /// <inheritdoc />
        public string Name { get; } = "SystemCache";

        /// <inheritdoc />
        public void SetObject(string key, object value, int seconds = 7200)
        {
            var Policy = new CacheItemPolicy()
            {
                AbsoluteExpiration = DateTime.Now.AddSeconds(seconds)
            };
            cache.Set(key, value, Policy);
        }

        /// <inheritdoc />
        public object GetObject(string key)
        {
            if (IsContain(key))
            {
                return cache.Get(key);
            }
            return null;
        }

        /// <inheritdoc />
        public T GetObject<T>(string key)
        {
            if (IsContain(key))
            {
                return (T)cache.Get(key);
            }
            return default(T);
        }

        /// <inheritdoc />
        public void RemoveObject(string key)
        {
            cache.Remove(key);
        }

        /// <inheritdoc />
        public void Clear()
        {
            foreach (var item in cache)
            {
                RemoveObject(item.Key);
            }
        }

        /// <inheritdoc />
        public bool IsContain(string key)
        {
            return cache.Contains(key);
        }

        /// <inheritdoc />
        public void Dispose()
        {
            cache?.Dispose();
        }

    }
}
